#include "stdafx.h"
#include "PatientEvent.h"

//Data structure:
//EventType	data[0]		-> type of event (for all events)
//(u_char)	data[1]		-> size of the rest of the data structure
//(byte)	data[2]		-> type
//(char*)	data[2+]	-> value
int serializePatientEvent(PatientEvent event, char* buffer){
	u_int bytesWritten = sizeof(event.type) + strlen(event.value.c_str()); // the size of the rest of the buffer

	u_char buffer_size = getPatientBufferSize(event);
	ZeroMemory(buffer, buffer_size);

	if(buffer != NULL && buffer_size > 0){		
		buffer[0] = PATIENT_EVENT;
		buffer[1] = bytesWritten;
		buffer[2] = event.type;

		char* dst = (buffer + sizeof(PATIENT_EVENT) + sizeof(bytesWritten) + sizeof(event.value)); // gives an index to start writing the alarm message string
		const char* str = event.value.c_str();
		size_t len = strlen(event.value.c_str());

		for (u_int i = 0; i < len; i++) {
			buffer[i+3] = str[i];
		}

		return 0;
	}else{ 
		fprintf(stdout, "Meh. The buffer is NULL or the buffer_size is too small (0 or less)");
		return -1;
	}
}

//Data structure:
//EventType	data[0]		-> type of event (for all events)
//(u_char)	data[1]		-> size of the rest of the data structure
//(byte)	data[2]		-> type
//(char*)	data[2+]	-> value

int deserializePatientEvent(char* buffer, PatientEvent *event){
	if(buffer != NULL){
		// event type is in the 0th spot
		EventType eventType = (EventType)buffer[0];
		if(eventType != PATIENT_EVENT){
			fprintf(stdout, "Deserialization failed: The type of event is not PatientEvent. EventType = %d\n", buffer[0]);
			return -1;
		}

		event->type = buffer[2]; // type is in 2nd spot		

		//create pointer to text
		char* textPtr = (buffer + 3); 

		std::string eventText(textPtr);
		event->value = eventText;

		return 0;
	}else{
		fprintf(stdout, "Deserialization failed: Buffer not allocated or too small");
		return -1;
	}
}

int getPatientBufferSize(PatientEvent event) {
	u_int bytesWritten = sizeof(event.type) + strlen(event.value.c_str()); // the size of the rest of the buffer
	
	//WARNING: sizeof(ALARM_EVENT) might differ in different compilers
	//See current C99 Standard Draft : http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
	//Section : 6.7.2.2 Enumeration specifiers

	return sizeof(PATIENT_EVENT) + sizeof(bytesWritten) + sizeof(event.type) + strlen(event.value.c_str());
}
